﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CoreData;
using ActionServices;

namespace ZidoniCMS.Controllers
{
    public class ProductController : BaseController
    {
        //
        // GET: /Product/
        public ProductController(IProductActionService _product, IProductAttributeActionService _attribute,
            ICategoryActionService _category, ISearchActionService _search, IConfigurationActionService _config,
            IEmailTemplateActionService _emailtemplate, IEmailListActionService _emailist)
            : base(_product, _attribute, _category, _search, _config,_emailtemplate, _emailist)
        { }

        static List<Product> ProductViewed = new List<Product>();
        static string name = "";
        static string manufac = "0";
        static string price = "0";

        /// <summary>
        /// Hiển thị tất cả sản phẩm 
        /// Phân trang sản phẩm
        /// Chọn kích thước trang ( PageSize)
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(int page = 1, int PageSize = 12, FormCollection frm = null)
        {

            SetupSearch(frm);
            IList<Product> model = ProductService.GetListByLINQ(x => x.Active == true).OrderBy(x => x.ID).ToList();
            if (model != null && model.Count <= PageSize)
                page = 1;
            ViewBag.page = page;
            ViewBag.PageSize = PageSize;
            int pagesize = (int)ViewBag.PageSize;
            ViewBag.TotalPage = Convert.ToInt32(Math.Ceiling((double)model.Count() / (int)ViewBag.PageSize));
            return View(model.OrderByDescending(x => x.ID).Skip((page - 1) * pagesize).Take(pagesize).ToList());
        }

        public ActionResult _ViewedProduct()
        {
            return PartialView();
        }
        /// <summary>
        /// Hiển thị chi tiết sản phẩm
        /// </summary>
        /// <returns></returns>
        public ActionResult Details(long Id)
        {
            string link = "";
            var product = ProductService.GetByID(Id);
            if (Session["ListViewedProduct"] == null)
            {
                ProductViewed.Clear();
            }

            var existP = ProductViewed.Where(c => c.ID == Id);
            if (existP.Count() == 0)
            {
                ProductViewed.Add(product);
                Session["ListViewedProduct"] = ProductViewed;
            }

            var category = CategoryService.GetByID(product.CateID);
            if (category == null) {
                category = new Category();
            }
            var attribute = ProductAttributeService.GetListByProductID(Id);
            if (attribute == null) {
                attribute = new List<ProductAttribute>();
            }
            Product model = new Product();
            model = product;
            model.ProductAttributeExt = attribute;
            model.CategoryNameExt = category.Name;
            model.View = model.View + 1;
            model.UpdateDate = model.UpdateDate;
            ProductService.Save(model, ref link);
            return View(model);
        }
        /// <summary>
        /// Lấy các Attribute là hình ảnh
        /// </summary>
        /// <param name="id">Id của sản phẩm</param>
        /// <returns></returns>
        public ActionResult ProductAttributeImage(int id) {
            var data = ProductAttributeService.GetListByLINQ(x => x.ProductID == id && x.AttributeID == 1).ToList();
            if (data.Count() > 0)
            {
                var product = ProductService.GetByID(id);
                ViewBag.TitleName = product.Name;
                ViewBag.MainImage = product.Image;
                return View(data);
            }
            else {
                return RedirectToAction("Details", new { Id = id });
            }
        }
        /// <summary>
        /// Breadcrumb cho phan danh muc va san pham
        /// </summary>
        /// <param name="Id">Id cua danh muc con cuoi cung dung de de quy ra cac thang cha</param>
        /// <param name="name">Ten cua breadcrumb vi du như khi show san pham se co ten san pham o cuoi, danh muc ko can</param>
        /// <returns></returns>
        public ActionResult _BreadCrumb(long Id, string name)
        {
            Product model = new Product();
            //Get category by Id dung de tra ve 
            var category = CategoryService.GetByID(Id);
            //Get toan bo category
            var Listcategory = CategoryService.GetList();
            model.CategoryNameExt = category.Name;
            model.CategoryListExt = Listcategory;
            model.CateID = category.ID;
            model.Name = name;
            return PartialView(model);
        }
        
        /// <summary>
        /// Sản phẩm liên quan
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ActionResult _RelatedProduct(int Id)
        {
            List<Product> model = new List<Product>();
            model = ProductService.GetListByLINQ(x => x.Active && x.CateID == Id).OrderByDescending(x => Guid.NewGuid()).Take(6).ToList();
            if (model.Count < 0)
            {
                model = ProductService.GetListByLINQ(x => x.Active).OrderByDescending(x => Guid.NewGuid()).Take(6).ToList();
            }
            return PartialView(model);
        }

        void SetupSearch(FormCollection frm)
        {
            if (frm.Count != 0)
            {
                name = frm["txtname"];
                manufac = frm["searchmanufac"];
                price = frm["searchprice"];
            }

            //ProductService.GetListByLINQ(x=>x.Active);
            if (string.IsNullOrEmpty(frm["searchmanufac"]))
            {
                frm["searchmanufac"] = manufac;
            }
            if (string.IsNullOrEmpty(frm["searchprice"]))
                frm["searchprice"] = price;
            try
            {
                var testprice = int.Parse(frm["searchprice"]);
            }
            catch { frm["searchprice"] = "0"; }
            try
            {
                var testmenufac = int.Parse(frm["searchmanufac"]);
            }
            catch { frm["searchmanufac"] = "0"; }
            ViewBag.GetListPrice = ProductService.GetListSearchPrice(int.Parse(frm["searchprice"]));
        }

        /// <summary>
        /// Sản phẩm theo danh mục 
        /// </summary>
        /// <param name="p"></param>
        /// <param name="PageSize"></param>
        /// <param name="Id"></param>
        /// <param name="ProductName"></param>
        /// <param name="Price"></param>
        /// <param name="Manufacturer"></param>
        /// <returns></returns>
        public ActionResult ProductCategory(int page = 1, int pageSize = 12, int Id = 0, FormCollection frm = null)
        {

            if (Id == 0)
                return View("Error");
            var cat = CategoryService.GetByID(Id);
            if (cat == null)
                return View("Error");

            List<Product> model = ProductService.GetListByCategory(Id).ToList();
            if (model.Count > 0)
            {
                //Nhằm lấy luôn của cả category con
                var LstCatParent = CategoryService.GetListByLINQ(c => c.ParentID == cat.ID);
                foreach (var item in LstCatParent)
                {
                    var p = ProductService.GetListByLINQ(c => c.CateID == item.ID);
                    if (p != null && p.Count() != 0)
                    {
                        model.AddRange(p);
                    }
                    AddChildProduct(item.ID, model);
                }
                ViewBag.page = page;
                ViewBag.PageSize = pageSize;
                ViewBag.TotalPage = (int)Math.Ceiling((float)model.Count / (float)pageSize);
                model = model.OrderByDescending(x => x.ID).Skip((page - 1) * pageSize).Take(pageSize).ToList();

                ViewBag.Title = cat.Name;
                ViewBag.CatId = cat.ID.ToString();
                ViewBag.Link = cat.Link;
            }
            return View(model);
        }
        /// <summary>
        /// Show list product by Category Id ----- Đáng ra nên viết trong servie nhưng làm biếng quá
        /// </summary>
        /// <param name="CatId">Category Id</param>
        /// <returns></returns>
        public ActionResult _ShowProductByCategory(int CatId)
        {
            List<Product> model = ProductService.GetListByCategory(CatId).ToList();
            var LstCatParent = CategoryService.GetListByLINQ(c => c.ParentID == CatId);
            foreach (var item in LstCatParent)
            {
                var p = ProductService.GetListByLINQ(c => c.CateID == item.ID);
                if (p != null && p.Count() != 0)
                {
                    model.AddRange(p);
                }
                AddChildProduct(item.ID, model);
            }
            model = model.Take(6).ToList();
            return PartialView(model);
        }

        public void AddChildProduct(long categoryid, List<Product> _listproduct)
        {
            var LstCatChild = CategoryService.GetListByLINQ(c => c.ParentID == categoryid);
            if (LstCatChild != null && LstCatChild.Count() != 0)
            {
                foreach (var item in LstCatChild)
                {
                    var p = ProductService.GetListByLINQ(c => c.CateID == item.ID);
                    if (p != null && p.Count() != 0)
                    {
                        _listproduct.AddRange(p);
                    }
                    //AddChildProduct(item.ID, _listproduct);
                }
            }
        }
    }
}